package com.ys.otms.services.impl;

import com.sun.mail.imap.protocol.ID;
import com.ys.otms.dao.IDeductionsDao;
import com.ys.otms.dao.IShipDao;
import com.ys.otms.dto.*;
import com.ys.otms.services.IDeductionsServices;
import com.ys.otms.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;

/**
 * Created by Administrator on 2018/10/26.
 */
@Service
public class DeductionsServiceImpl implements IDeductionsServices {

    private static Logger logger = LoggerFactory.getLogger(DeductionsServiceImpl.class);
    @Autowired
    private IDeductionsDao iDeductionsDao;
    @Autowired
    private IShipDao iShipDao;
    @Override
    public JSONObject generatingOrder(HttpServletRequest request) throws Exception {
        JSONObject obj = JsonUtil.getJSONObject(request);
        logger.info("DeductionsServiceImpl generatingOrder start obj{}",obj);
        String consumeTypeId =JsonUtil.getJSONObjectString(obj,"consumeTypeId");
        JSONArray jsonArray = JsonUtil.getJSONArray(obj,"shipList");
        JSONObject jsonObject = new JSONObject();
        double totalMoney =0.0;
        ParamDto paramDto = new ParamDto();
        paramDto.setConsumeTypeId(Integer.parseInt(consumeTypeId));
        ConsumeTypeDto consumeTypeDto = iDeductionsDao.selectConsumeTypeByConsumeTypeId(paramDto);
        if (consumeTypeDto ==null){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","没有该消费项目！");
            return jsonObject;
        }
        if (jsonArray.size()>0){
                totalMoney = consumeTypeDto.getMoney()*jsonArray.size();
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("MSG","没有选择船舶！");
            return jsonObject;
        }
        paramDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        LeftAmountDto leftAmountDto = iDeductionsDao.selectLeftAmountByCompanyId(paramDto);
        if(null ==leftAmountDto||leftAmountDto.getLeftAmount()<totalMoney) {
            jsonObject.put("SUCCESS",false);
            jsonObject.put("FLAG",false);
            jsonObject.put("MSG","账户余额不足，生成订单失败！");
            return jsonObject;
        }
        else {
            jsonObject.put("leftAmount",leftAmountDto.getLeftAmount());
        }
        ConsumeDto consumeDto = new ConsumeDto();
        consumeDto.setConsumeMoney(totalMoney);
        consumeDto.setConsumeTime(new Timestamp((new Date()).getTime()));
        consumeDto.setConsumeTypeId(Integer.parseInt(consumeTypeId));
        consumeDto.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        consumeDto.setUserid(Integer.parseInt((String) request.getSession().getAttribute("SESSION_USER_ID")));
        consumeDto.setJiShiId(0);
        consumeDto.setConsumeStatus(0);
        iDeductionsDao.insertConsume(consumeDto);
        jsonObject.put("SUCCESS",true);
        jsonObject.put("totalMoney",totalMoney);
        jsonObject.put("consumeId",consumeDto.getId());
        return jsonObject;
    }

    @Override
    @Transactional
    public JSONObject deductionsMethod(HttpServletRequest request,JSONObject obj) throws Exception {
        logger.info("DeductionsServiceImpl deductionsMethod start obj{}",obj);
        String consumeId = JsonUtil.getJSONObjectString(obj,"consumeId");
        JSONArray jsonArray = JsonUtil.getJSONArray(obj,"shipList");
        ParamDto paramDto = new ParamDto();
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isNotEmpty(consumeId)){
            paramDto.setConsumeId(Integer.parseInt(consumeId));
        }else{
            jsonObject.put("SUCCESS",false);
            jsonObject.put("STATUS",0);
            jsonObject.put("MSG","扣费失败，系统错误！");
            return jsonObject;
        }
        if (jsonArray.size() ==0){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("STATUS",0);
            jsonObject.put("MSG","扣费失败，系统错误！");
            return jsonObject;
        }
        ConsumeDto consumeDto = iDeductionsDao.selectConsumeById(paramDto);
        if (consumeDto ==null){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("STATUS",0);
            jsonObject.put("MSG","扣费失败，系统错误！");
            return jsonObject;
        }
        paramDto.setUserId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        logger.info("paramDto:",paramDto);
        LeftAmountDto leftAmountDto = iDeductionsDao.selectLeftAmountByCompanyId(paramDto);
        if (leftAmountDto == null || leftAmountDto.getLeftAmount() ==0 || leftAmountDto.getLeftAmount()<consumeDto.getConsumeMoney()){
            jsonObject.put("SUCCESS",false);
            jsonObject.put("STATUS",1);
            jsonObject.put("MSG","扣费失败，账户余额不足，请充值！");
            return jsonObject;
        }
        LeftAmountDto leftAmountDtos = new LeftAmountDto();
        leftAmountDtos.setLeftAmount(leftAmountDto.getLeftAmount()-consumeDto.getConsumeMoney());
        leftAmountDtos.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
        iDeductionsDao.updateLeftAmountMoney(leftAmountDtos);
        paramDto.setConsumeStatus(1);
        iDeductionsDao.updateConsumeById(paramDto);
        List<UserShipDto> userShipDtos = new ArrayList<>();
        UserShipDto userShipDto =null;
        if(consumeDto.getConsumeTypeId()==2 || consumeDto.getConsumeTypeId()==3){
            for (int i = 0; i <jsonArray.size() ; i++) {
                JSONObject shipIdObj = (JSONObject) jsonArray.get(i);
                userShipDto = new UserShipDto();
                userShipDto.setCompanyId(Integer.parseInt((String) request.getSession().getAttribute("SESSION_COMPANY_ID")));
                userShipDto.setShipId(Integer.parseInt(shipIdObj.getString("shipId")));
                userShipDto.setCreateTime(new Timestamp((new Date()).getTime()));
                userShipDto.setStartTime(new Timestamp((new Date()).getTime()));
                userShipDto.setEndTime(DateUtil.dateOfCalculation(new Timestamp((new Date()).getTime()), consumeDto.getConsumeTypeId()));
                userShipDto.setConsumeId(Integer.parseInt(consumeId));
                userShipDtos.add(userShipDto);
            }
            List<UserShipDto> userShipDtoList = new ArrayList<>();
            List<UserShipDto> userShipDtoList1 = new ArrayList<>();
            for (int i = 0; i <userShipDtos.size() ; i++) {
                paramDto.setCompanyId(userShipDtos.get(i).getCompanyId());
                paramDto.setShipId(userShipDtos.get(i).getShipId());
                UserShipDto userShipDto1 = iShipDao.selectUserShip(paramDto);
                if (userShipDto1 == null){
                    continue;
                }
                userShipDto1.setUsStatus(1);
                userShipDto1.setCreateTime(userShipDtos.get(i).getCreateTime());
                userShipDto1.setStartTime(userShipDtos.get(i).getStartTime());
                userShipDto1.setEndTime(userShipDtos.get(i).getEndTime());
                userShipDtoList.add(userShipDto1);
            }
            if (userShipDtoList.size()>0){
                for (int i = 0; i < userShipDtos.size(); i++) {
                    for (int j = 0; j <userShipDtoList.size() ; j++) {
                        if (userShipDtos.get(i).getShipId().equals(userShipDtoList.get(j).getShipId())&& userShipDtos.get(i).getCompanyId().equals(userShipDtoList.get(j).getCompanyId())){
                            break;
                        }
                        if (j==userShipDtoList.size()-1){
                            userShipDto = new UserShipDto();
                            userShipDto.setCompanyId(userShipDtos.get(i).getCompanyId());
                            userShipDto.setShipId(userShipDtos.get(i).getShipId());
                            userShipDto.setCreateTime(userShipDtos.get(i).getCreateTime());
                            userShipDto.setStartTime(userShipDtos.get(i).getStartTime());
                            userShipDto.setEndTime(userShipDtos.get(i).getEndTime());
                            userShipDto.setUsStatus(1);
                            userShipDto.setConsumeId(Integer.parseInt(consumeId));
                            userShipDtoList1.add(userShipDto);
                        }
                    }
                }
                if (userShipDtoList1.size()>0){
                    iDeductionsDao.insetUserAndShip(userShipDtoList1);
                }
                for (int i = 0; i <userShipDtoList.size() ; i++) {
                    iDeductionsDao.updateUserAndShip(userShipDtoList.get(i));
                }
                jsonObject.put("MSG", "已添加到自有运力");
            }else{
                iDeductionsDao.insetUserAndShip(userShipDtos);
                jsonObject.put("MSG", "已添加到自有运力");
            }
        }
        jsonObject.put("SUCCESS", true);
        return jsonObject;

    }

}
